<template>
	<section class="wrapper">
		<div style="padding: 20px;">
			<el-dialog v-model="state.agency_visible" width="360">
				<template #header="{ close, titleId, titleClass }">
					<div class="my-header flex_between_center">
						<h4 style="margin-top: 0px;margin-bottom: 0px;" :id="titleId" :class="titleClass">
							{{state.add_or_edit_title}}
						</h4>
					</div>
				</template>
				<el-form ref="formRef" :model="state.add_ruleform" :rules="formRules" class="demo-form-inline"
					label-width="80px" :key="state.add_or_edit_title">
					<el-form-item label="代理类型" prop="protocol">
						<el-select v-model="state.add_ruleform.protocol" placeholder="请选择代理类型" style="width: 240px;">
							<el-option label="socks5" value="socks5" />
							<el-option label="https" value="https" />
							<el-option label="http" value="http" />
						</el-select>
					</el-form-item>
					<el-form-item label="代理名称" prop="proxy_name">
						<el-input v-model="state.add_ruleform.proxy_name" clearable style="width: 240px;" />
					</el-form-item>
					<el-form-item label="IP" prop="host">
						<el-input v-model="state.add_ruleform.host" clearable style="width: 240px;"
							placeholder="例如：192.168.1.1" />
					</el-form-item>
					<el-form-item label="端口" prop="port">
						<el-input v-model="state.add_ruleform.port" clearable style="width: 240px;"
							placeholder="1-65535" />
					</el-form-item>
					<el-form-item label="账号" prop="user_name">
						<el-input v-model="state.add_ruleform.user_name" clearable style="width: 240px;" />
					</el-form-item>
					<el-form-item label="密码" prop="password">
						<el-input v-model="state.add_ruleform.password" clearable style="width: 240px;" />
					</el-form-item>
					<el-form-item label="备注">
						<el-input v-model="state.add_ruleform.remark" clearable style="width: 240px;" />
					</el-form-item>
					<el-form-item label="">
						<el-button type="primary" link @click="detection_network">网络检测</el-button>
						<el-icon v-if="state.network_loading" :class="state.network_loading?'is-loading_icon':''">
							<Loading />
						</el-icon>
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button type="primary" @click="validateAndSubmit"
							:loading="state.agency_vloading">确认</el-button>
						<el-button @click="state.agency_visible = false">取消</el-button>
					</div>
				</template>
			</el-dialog>
			<el-dialog v-model="state.agency_detail_visible" width="500">
				<template #header="{ close, titleId, titleClass }">
					<div class="my-header flex_between_center">
						<h4 style="margin-top: 0px;margin-bottom: 0px;" :id="titleId" :class="titleClass">代理详情</h4>
					</div>
				</template>
				<el-descriptions title="" :column="2">
					<el-descriptions-item label="代理类型">
						<div class="flex_center_center">
							<span>{{state.agency_detail.protocol}}</span>
							<el-icon size="18" v-if="state.agency_detail.protocol" class="copyicon"
								@click="copyProtocol(state.agency_detail.protocol)">
								<CopyDocument />
							</el-icon>
						</div>

					</el-descriptions-item>
					<el-descriptions-item label="代理名称">
						<div class="flex_center_center">
							<span>{{state.agency_detail.proxy_name}}</span>
							<el-icon size="18" v-if="state.agency_detail.proxy_name" class="copyicon"
								@click="copyProtocol(state.agency_detail.proxy_name)">
								<CopyDocument />
							</el-icon>
						</div>
					</el-descriptions-item>
					<el-descriptions-item label="IP">
						<div class="flex_center_center">
							<span>{{state.agency_detail.host}}</span>
							<el-icon size="18" v-if="state.agency_detail.host" class="copyicon"
								@click="copyProtocol(state.agency_detail.host)">
								<CopyDocument />
							</el-icon>
						</div>
					</el-descriptions-item>
					<el-descriptions-item label="端口">
						<div class="flex_center_center">
							<span>{{state.agency_detail.port}}</span>
							<el-icon size="18" v-if="state.agency_detail.port" class="copyicon"
								@click="copyProtocol(state.agency_detail.port)">
								<CopyDocument />
							</el-icon>
						</div>
					</el-descriptions-item>
					<el-descriptions-item label="账号">
						<div class="flex_center_center">
							<span>{{state.agency_detail.user_name}}</span>
							<el-icon size="18" v-if="state.agency_detail.user_name" class="copyicon"
								@click="copyProtocol(state.agency_detail.user_name)">
								<CopyDocument />
							</el-icon>
						</div>
					</el-descriptions-item>
					<el-descriptions-item label="密码">
						<div class="flex_center_center">
							<span>{{state.agency_detail.password}}</span>
							<el-icon size="18" v-if="state.agency_detail.password" class="copyicon"
								@click="copyProtocol(state.agency_detail.password)">
								<CopyDocument />
							</el-icon>
						</div>
					</el-descriptions-item>
					<el-descriptions-item label="备注">
						<div class="flex_center_center">
							<span>{{state.agency_detail.remark}}</span>
							<el-icon size="18" v-if="state.agency_detail.remark" class="copyicon"
								@click="copyProtocol(state.agency_detail.remark)">
								<CopyDocument />
							</el-icon>
						</div>
					</el-descriptions-item>
				</el-descriptions>
			</el-dialog>
			<Phone_List_Dialog v-model:Cloud_dialog_flag="state.cloudDialogVisible" :is_bind_phone="state.is_bind_phone"
				:pre-selected-ids="state.parentSelectedIds" @confirm="handleCloudConfirm"
				@cancel="state.parentSelectedIds=[]" />
			<div class="bottom_div">
				<el-form :inline="true" :model="state.agency_query_from" class="demo-form-inline">
					<el-form-item label="">
						<el-input v-model="state.agency_query_from.agency_name" placeholder="请输入代理名称">
							<template #suffix>
								<el-icon style="cursor: pointer;" @click="Get_agency_list">
									<Search />
								</el-icon>
							</template>
						</el-input>
					</el-form-item>
					<el-form-item label="IP类型">
						<el-select v-model="state.agency_query_from.agency_affiliation" style="width: 200px"
							placeholder="请选择" clearable @change="Get_agency_list">
							<el-option label="静态IP" value="static" />
							<el-option label="动态IP" value="dynamic" />
						</el-select>
					</el-form-item>
					<el-form-item label="状态">
						<el-select v-model="state.agency_query_from.status" style="width: 200px" placeholder="请选择"
							clearable @change="Get_agency_list">
							<el-option label="正常" value="1" />
							<!-- 	<el-option label="即将过期" value="" />
							<el-option label="已过期" value=""/> -->
							<el-option label="异常" value="2" />
							<!-- <el-option label="检测异常" value="" /> -->
						</el-select>
					</el-form-item>
				</el-form>
				<div style="margin-bottom: 20px;">
					<el-button type="danger" plain @click="condition_delete_agency()"
						:disabled="state.checked_agency_list.length==0">删除</el-button>
					<el-popover placement="bottom" trigger="click" popper-style="padding:0;">
						<template #reference>
							<el-button type="primary" plain>添加代理</el-button>
						</template>
						<div class="fun_options">
							<p @click="add_agency_init">单个添加代理</p>
							<!-- <p @click="add_agency_init">批量添加代理</p> -->
						</div>
					</el-popover>
					<!-- 	<el-button type="primary" plain>购买代理</el-button>
					<el-button type="primary" plain>续费代理</el-button> -->
				</div>
				<el-table :data="state.agency_tableData" style="width: 100%" v-loading="state.table_loading"
					height="600" :header-cell-style="{ textAlign: 'center',backgroundColor: '#fafafa',color:'#333'}"
					:cell-style="{ textAlign: 'center'}" @selection-change="handleSelectionChange"
					@row-click="look_agency_detail">
					<el-table-column type="selection" width="55" />
					<el-table-column type="index" label="序号" width="55" />
					<el-table-column prop="type" label="IP类型">
						<template #default="scope">
							<p>{{ scope.row.type=='static'?'静态IP':'动态IP'}}</p>
						</template>
					</el-table-column>
					<el-table-column prop="proxy_name" label="代理名称" show-overflow-tooltip />
					<el-table-column prop="proxy_name" label="来源">
						<template #default="scope">
							<el-tag type="primary">自有</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="port" label="IP端口" show-overflow-tooltip>
						<template #default="scope">
							<p>{{scope.row.host}}:{{scope.row.port}}</p>
						</template>
					</el-table-column>
					<el-table-column prop="status" label="代理状态">
						<template #default="scope">
							<el-tag v-if="scope.row.status==1" type="success">正常</el-tag>
							<el-tag v-else type="danger">异常</el-tag>
						</template>
					</el-table-column>
					<el-table-column prop="country_code" label="代理归属" show-overflow-tooltip>
						<template #default="scope">
							<p>{{ scope.row.country_code}} - {{scope.row.city}}</p>
						</template>
					</el-table-column>
					<el-table-column prop="bind_num" label="绑定数量" show-overflow-tooltip />
					<el-table-column prop="protocol" label="协议类型" show-overflow-tooltip />
					<!-- <el-table-column prop="name" label="有效时间" /> -->
					<el-table-column fixed="right" label="操作" min-width="120">
						<template #default="scope">
							<el-button link type="primary" size="small"
								@click.stop="show_phone_diglog(scope.row,true)">绑定</el-button>
							<el-button link type="primary" size="small" @click.stop="show_phone_diglog(scope.row,false)"
								:disabled="scope.row.bind_instance_list.length==0">解绑</el-button>
							<el-button link type="primary" size="small"
								@click.stop="show_agency_dialog(scope.row)">编辑</el-button>
							<el-button link type="danger" size="small"
								@click.stop="delete_agency(scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<div class="pagination_div">
					<el-pagination v-model:current-page="state.currentPage" v-model:page-size="state.pageSize"
						:page-sizes="state.pagesizes" :background="true"
						layout="total, sizes, prev, pager, next, jumper" :total="state.agency_tableData_length"
						@size-change="handleSizeChange" @current-change="handleCurrentChange" />
				</div>
			</div>
		</div>
	</section>
</template>

<script setup>
	import md5 from 'js-md5';
	import {
		ref,
		reactive,
		computed,
		onMounted,
		onUnmounted,
		getCurrentInstance,
		nextTick,
		watch,
	} from 'vue';
	import request from '@/utils'
	import {
		ElMessage,
		ElMessageBox,
		ElLoading,
		ElIcon
	} from 'element-plus';
	import {
		Search
	} from '@element-plus/icons-vue';
	import Phone_List_Dialog from '@/components/Phone_List_Dialog'
	import {
		useStore
	} from 'vuex';
	const store = useStore();
	const formRef = ref(); // 表单引用
	const state = reactive({
		agency_query_from: { //代理列表查询表单
			agency_name: '',
			agency_affiliation: '',
			status: null
		},
		add_ruleform: { //添加代理表单数据
			proxy_name: '',
			protocol: '',
			host: '',
			port: '',
			user_name: '',
			password: '',
			remark: ''
		},
		pagesizes: [10, 20, 30, 50, 100, 200], //可供用户选择的分页器的每页数据量数组
		currentPage: 1, //分页器当前页
		pageSize: 10, //分页器每页数据量
		agency_tableData_length: '', //代理列表数据长度
		agency_visible: false, //添加或修改代理表单开关
		agency_detail_visible: false, //查看代理详情内容弹框开关
		agency_detail: {}, //代理详情对象
		agency_vloading: false, //添加代理loading开关
		agency_tableData: [], //代理列表数据
		network_loading: false, //网络检测刷新图标开关
		table_loading: false, //代理列表刷新loading开关
		current_agency_id: null, //当前代理Id
		cloudDialogVisible: false, //云手机列表弹框组件开关
		checked_agency_list: [], // 存储选中的云手机
		add_or_edit_title: '添加代理',
		parentSelectedIds: [],
		is_bind_phone: false, //是绑定操作还是解绑操作
	});
	// 表单验证规则
	const formRules = {
		protocol: [{
			required: true,
			message: '请选择代理类型',
			trigger: 'change'
		}],
		proxy_name: [{
				required: true,
				message: '请输入代理名称',
				trigger: 'blur'
			},
			{
				min: 1,
				max: 15,
				message: '代理名称长度在 1 到 15 个字符',
				trigger: 'blur'
			}
		],
		host: [{
				required: true,
				message: '请输入IP地址',
				trigger: 'blur'
			},
			{
				validator: (rule, value, callback) => {
					if (!value) {
						callback(new Error('请输入IP地址'));
						return;
					}

					// IPv4 地址验证正则表达式
					const ipv4Regex =
						/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;

					if (!ipv4Regex.test(value)) {
						callback(new Error('请输入有效的IPv4地址（例如：192.168.1.1）'));
					} else {
						callback();
					}
				},
				trigger: 'blur'
			}
		],
		port: [{
				required: true,
				message: '请输入端口号',
				trigger: 'blur'
			},
			{
				validator: (rule, value, callback) => {
					if (!value) {
						callback(new Error('请输入端口号'));
						return;
					}
					// 检查是否为数字且没有小数点
					const portNumber = Number(value);
					if (isNaN(portNumber) || !Number.isInteger(portNumber)) {
						callback(new Error('端口号必须是整数'));
						return;
					}
					// 检查端口范围 (1-65535)
					if (portNumber < 1 || portNumber > 65535) {
						callback(new Error('端口号必须在 1-65535 范围内'));
					} else {
						callback();
					}
				},
				trigger: 'blur'
			}
		],
		user_name: [{
			min: 0,
			max: 50,
			message: '账号长度不能超过 50 个字符',
			trigger: 'blur'
		}],
		password: [{
			min: 0,
			max: 50,
			message: '密码长度不能超过 50 个字符',
			trigger: 'blur'
		}]
	};

	onMounted(async () => {
		await Get_agency_list();
	});
	//分页器的每页数据数量
	const handleSizeChange = (val) => {
		state.pageSize = val
		Get_agency_list()
	}
	//获取分页器当前页
	const handleCurrentChange = (val) => {
		state.currentPage = val
		Get_agency_list()
	}
	//添加代理弹窗弹出初始化函数
	const add_agency_init = () => {
		state.agency_visible = true;
		state.add_or_edit_title = '添加代理'
		state.add_ruleform = {
			proxy_name: '',
			protocol: '',
			host: '',
			port: '',
			user_name: '',
			password: '',
			remark: ''
		}
		// 重置表单
		nextTick(() => {
			if (formRef.value) {
				formRef.value.resetFields();
			}
		});
	}
	//编辑代理弹窗弹出初始化函数
	const show_agency_dialog = (row) => {
		state.add_or_edit_title = '编辑代理'
		state.agency_visible = true;
		state.add_ruleform = row
	}
	//获取代理列表数据
	const Get_agency_list = () => {
		state.table_loading = true
		var params = ``
		if (state.agency_query_from.agency_name) {
			params += `&name=${state.agency_query_from.agency_name}`
		}
		if (state.agency_query_from.status) {
			params += `&status=${state.agency_query_from.status}`
		}
		if (state.agency_query_from.agency_affiliation) {
			params += `&type=${state.agency_query_from.agency_affiliation}`
		}
		request.get(`/proxy/list?page=${state.currentPage}&pageSize=${state.pageSize}` + params).then((res) => {
			state.agency_tableData = res.data.data
			state.agency_tableData_length = res.data.total
			state.table_loading = false
		});
	}
	// 验证并提交表单
	const validateAndSubmit = async () => {
		if (!formRef.value) return;
		state.agency_vloading = true
		try {
			await formRef.value.validate();
			if (state.add_or_edit_title == '添加代理') {
				await add_agency_commit();
			} else {
				await edit_agency_commit()
			}
		} catch (error) {
			state.agency_vloading = false
			ElMessage.error('请检查添加代理表单填写是否正确');
		}
	}
	//查看代理内容详情
	const look_agency_detail = (row) => {
		state.agency_detail = row
		state.agency_detail_visible = true
	}
	//添加代理
	const add_agency_commit = async () => {
		try {
			const {
				port,
				user_name,
				proxy_name,
				...rest
			} = state.add_ruleform;
			const requestData = { //不同字段进行转接
				...rest,
				port: Number(port),
				username: user_name,
				name: proxy_name
			};
			const response = await request.post('/proxy/create', requestData);
			if (response.data.code === 200) {
				ElMessage.success('代理添加成功');
				state.agency_visible = false;
				state.agency_vloading = false
				// 刷新代理列表
				await Get_agency_list();
			} else {
				state.agency_vloading = false
			}
		} catch (error) {
			state.agency_vloading = false
		}
	}
	//编辑代理
	const edit_agency_commit = async () => {
		try {
			const {
				port,
				user_name,
				proxy_name,
				...rest
			} = state.add_ruleform;
			const requestData = { //不同字段进行转接
				...rest,
				port: Number(port),
				username: user_name,
				name: proxy_name
			};
			const response = await request.post('/proxy/update', requestData);
			if (response.data.code === 200) {
				ElMessage.success('代理编辑成功');
				state.agency_visible = false;
				state.agency_vloading = false
				await Get_agency_list();
			} else {
				state.agency_vloading = false
			}
		} catch (error) {
			state.agency_vloading = false
		}
	}
	//删除代理
	const delete_agency = async (row) => {
		ElMessageBox.confirm(
				'您确认删除该代理吗？',
				'警告', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				var delete_ids = []
				delete_ids.push(row.id)
				const requestData = {
					"ids": delete_ids
				};
				request.post('/proxy/delete', requestData).then((res) => {
					if (res.data.code === 200) {
						Get_agency_list()
						ElMessage.success('删除代理成功');
					}
				});
			})
			.catch(() => {})
	}
	//多选删除代理
	const condition_delete_agency = async () => {
		ElMessageBox.confirm(
				'您确认删除这些代理吗？',
				'警告', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				const requestData = {
					"ids": state.checked_agency_list.map(item => item.id)
				};
				request.post('/proxy/delete', requestData).then((res) => {
					if (res.data.code === 200) {
						Get_agency_list()
						ElMessage.success('删除代理成功');
					}
				});
			})
			.catch(() => {})
	}
	//表格check选中返回数据
	function handleSelectionChange(val) {
		state.checked_agency_list = val
	}
	//添加或编辑代理进行网络检测
	const detection_network = async () => {
		if (!formRef.value) return;
		try {
			// 只验证必要的字段
			await formRef.value.validateField(['protocol', 'proxy_name', 'host', 'port']);
			state.network_loading = true
			const {
				port,
				user_name,
				proxy_name,
				...rest
			} = state.add_ruleform;
			const requestData = { //不同字段进行转接
				...rest,
				port: Number(port),
				username: user_name,
				name: proxy_name
			};
			const response = await request.post('/proxy/detectip', requestData);
			if (response.data.code === 200) {
				state.network_loading = false
				ElMessage.success(`网络检测成功: 连接正常`);
			} else {
				ElMessage.error(response.data.msg || '网络检测失败');
				state.network_loading = false
			}
		} catch (error) {
			state.network_loading = false
		}
	}
	//云手机弹窗开启
	const show_phone_diglog = (row, type) => { //获取绑定或者未绑定代理的云手机列表数据
		var is_restart = false
		row.bind_instance_list.forEach((item, index) => {
			if (item.state != 1) {
				is_restart = true
				return;
			}
		})
		if (!is_restart) {
			request.get(`/proxy/related_instances?proxy_id=${type?0:row.id}`).then((res) => {
				if (res.data.code === 200) {
					if (res.data.data.length > 0) {
						state.current_agency_id = row.id
						state.is_bind_phone = type
						state.parentSelectedIds = res.data.data
						state.cloudDialogVisible = true
					} else {
						ElMessage.success('没有云手机可以绑定代理了');
					}
				}
			});
		} else {
			ElMessage.error('当前代理有云手机正在重启中');
		}
	}
	// 处理绑定或解绑确认选择
	const handleCloudConfirm = (selectedCloudsList) => {
		const idList = selectedCloudsList.map(item => item.id);
		if (idList.length > 0) {
			if (state.is_bind_phone) {
				const requestData = {
					"proxy_id": state.current_agency_id,
					"instance_id": idList
				};
				request.post('/proxy/bind_instance', requestData).then((res) => {
					if (res.data.code === 200) {
						Get_agency_list()
						ElMessage.success('绑定云手机成功');
					}
				});
			} else {
				const requestData = {
					"proxy_id": state.current_agency_id,
					"instance_id": idList
				};
				request.post('/proxy/unbind', requestData).then((res) => {
					if (res.data.code === 200) {
						Get_agency_list()
						ElMessage.success('解绑云手机成功');
					}
				});
			}
		}
	}
	// 复制字段内容到剪贴板
	const copyProtocol = async (copydata) => {
		try {
			// 使用现代 Clipboard API
			await navigator.clipboard.writeText(copydata)
			ElMessage.success(`已复制: ${copydata}`)
		} catch (err) {
			// 降级方案：使用传统的 execCommand
			fallbackCopyTextToClipboard(copydata)
		}
	}

	// 传统复制方法（兼容性方案）
	const fallbackCopyTextToClipboard = (text) => {
		const textArea = document.createElement('textarea')
		textArea.value = text
		textArea.style.position = 'fixed'
		textArea.style.opacity = '0'
		document.body.appendChild(textArea)
		textArea.focus()
		textArea.select()

		try {
			const successful = document.execCommand('copy')
			document.body.removeChild(textArea)
			if (successful) {
				ElMessage.success('内容已复制到剪切板')
			} else {
				ElMessage.error('复制失败')
			}
		} catch (err) {
			document.body.removeChild(textArea)
			ElMessage.error('复制失败')
		}
	}
	// 监听弹窗关闭，重置表单
	watch(() => state.agency_visible, (newVal) => {
		if (!newVal && formRef.value) {
			// 延迟重置，避免动画冲突
			setTimeout(() => {
				formRef.value.resetFields();
			}, 300);
		}
	});
</script>

<style lang="less" scoped>
	h2 {
		margin: 0;
		margin-left: 10px;
	}

	.wrapper {
		background-color: #fff;
		border-radius: 10px;
		position: relative;

		.bottom_div {
			margin-top: 20px;
			text-align: left;
		}

		.pagination_div {
			position: absolute;
			bottom: 20px;
			right: 20px;
		}
	}

	.is-loading_icon {
		animation: rotating 2s linear infinite;
	}

	@keyframes rotating {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	.copyicon {
		margin-left: 10px;
	}

	.copyicon:hover {
		cursor: pointer;
		color: #0062ff;
	}
</style>